﻿<template>
  <div class="app-wrapper">
    <GlobalHeader />
    <div class="app-content-wrapper">
      <div class="help-wrapper">
        <div class="page-search">
          <div class="search-title">嗨! 有什么需要帮助的吗?</div>

          <!-- 搜索框：回车/按钮触发搜索，清空退出搜索态 -->
          <div class="search-wrap">
            <el-input
              v-model="keyWords"
              class="search-input"
              size="large"
              clearable
              placeholder="输入问题，让我帮助你解答"
              @keyup.enter="onSearch"
              @clear="onClear"
            >
              <template #prefix>
                <img
                  class="search-icon"
                  src="https://qingqingrent.oss-cn-hangzhou.aliyuncs.com/backstage/xiaochengxu/helpcenter/search-icon.png"
                />
              </template>
            </el-input>

            <!-- 只有在非搜索状态时，才展示分割线与按钮 -->
            <i v-if="pageStatus !== 'search'" class="search-divider"></i>
            <el-button v-if="pageStatus !== 'search'" text class="search-btn" @click="onSearch">搜索</el-button>
          </div>
        </div>

        <div class="page-bot-wrapper">
          <div class="page-bot">
            <!-- 搜索态隐藏左侧树；非搜索态显示 -->
            <div class="bot-left" v-if="pageStatus !== 'search'">
              <MenuTree
                :menu-list="menuList"
                :replace-fields="{ name: 'categoryName', value: 'id', children: 'children', contents: 'contents' }"
                @select="handleMenuSelect"
              />
            </div>

            <div class="bot-right">
              <!-- 分类列表（非搜索态） -->
              <CategoryList v-if="pageStatus === 'category'" :list="contents" :loading="false" @select="openDetail" />
              <!-- 搜索结果（搜索态） -->
              <SearchList v-if="pageStatus === 'search'" ref="SearchRef" :keywords="keyWords" @select="openDetail" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import GlobalHeader from "./components/GlobalHeader.vue";
  import MenuTree from "./components/MenuTree.vue";
  import CategoryList from "./components/CategoryList.vue";
  import SearchList from "./components/SearchList.vue";
  import { ROUTE_PATHS } from "@/utils/const";
  // const router = useRouter();
  const SearchRef = ref(null);

  const keyWords = ref("");
  const pageStatus = ref("category"); // recent / search / category

  // 左侧菜单 + 右侧选中内容
  const menuList = ref([]);
  const selectedNode = ref(null);
  const contents = computed(() => (Array.isArray(selectedNode.value?.contents) ? selectedNode.value.contents : []));

  onMounted(async () => {
    await loadMenuTree();
  });

  /* ========== 搜索相关 ========== */
  function onSearch() {
    const kw = keyWords.value?.trim();
    if (!kw) return onClear(); // 空词直接退出搜索态
    pageStatus.value = "search";
    SearchRef.value?.goSearch?.({ keywords: kw });
  }
  function onClear() {
    keyWords.value = "";
    if (pageStatus.value === "search") pageStatus.value = "category";
  }
  watch(keyWords, v => {
    if (!v && pageStatus.value === "search") pageStatus.value = "category";
  });

  /* ========== 左侧选择 ========== */
  function handleMenuSelect(payload) {
    pageStatus.value = "category";
    if (payload && typeof payload === "object") {
      selectedNode.value = payload;
    } else {
      const node = findNodeById(menuList.value, payload, { value: "id", children: "children" });
      selectedNode.value = node;
    }
  }

  function openDetail(item) {
    const contentId = item.id || item.contentId;
    if (!contentId) {
      console.error("内容ID不存在:", item);
      return;
    }
    const url = `${location.origin}${location.pathname}#${ROUTE_PATHS.SERVICE_CENTER_DETAIL}?id=${encodeURIComponent(contentId)}`;
    window.open(url, "_blank");
  }

  /* ========== API ========== */
  async function loadMenuTree() {
    try {
      const res = await Api.service.GetSelectCategoryContent({});
      const data = res?.data ?? res;
      menuList.value = Array.isArray(data?.data) ? data.data : Array.isArray(data) ? data : [];
    } catch (e) {
      console.error("[GetSelectCategoryContent] error:", e);
      menuList.value = [];
    }
  }

  /* ========== 工具 ========== */
  function findNodeById(list = [], id, fields) {
    if (id == null || id === "") return null;
    const idKey = fields?.value || "id";
    const childrenKey = fields?.children || "children";
    const sid = String(id);
    const stack = Array.isArray(list) ? [...list] : [];
    while (stack.length) {
      const cur = stack.shift();
      if (!cur) continue;
      if (String(cur[idKey]) === sid) return cur;
      const kids = cur[childrenKey];
      if (Array.isArray(kids) && kids.length) stack.push(...kids);
    }
    return null;
  }
</script>

<style lang="scss" scoped>
  /* 细调 el-input 内容左右内边距（保持你的原效果） */
  :deep(.el-input--large .el-input__wrapper) {
    padding: 1px 0 1px 15px !important;
  }

  /* 外层容器：固定 2px 边框，不抖动，只变颜色 */
  .search-wrap {
    position: relative;
    z-index: 10; /* 把搜索条压在上面 */
    width: 720px;
    height: 54px;
    padding: 0 12px 0 0; /* 右侧给按钮留点内边距 */
    display: flex;
    align-items: center;
    box-sizing: border-box;
    // border: 2px solid var(--bg); /* 固定宽度 */
    border: 2px solid #5947f1; /* 固定宽度 */
    border-radius: 8px;
    background: #fff;
    box-shadow: 0px 4px 16px 0px #4753ff1a;
    transition: border-color 0.18s ease;

    &:hover {
      // border-color: var(--bd);
      border-color: #5947f1;
    }
  }

  /* 让 el-input 看起来“无边框”，并合并你两处重复样式 */
  .search-input {
    flex: 1;
    width: 720px; /* 保留你原来在 .page-search 里的尺寸 */
    height: 54px;
    border-radius: 8px;
    overflow: hidden;

    --el-input-border-color: transparent;
    --el-input-hover-border-color: transparent;
    --el-input-focus-border-color: transparent;
    --el-input-bg-color: transparent;
    --el-input-border-radius: 12px; /* 保留你的设置 */

    /* 旧的 append 定制仍保留，虽然此处未使用 */
    :deep(.el-input-group__append) {
      padding: 0;
      border: none;
      background: transparent;
    }
    .search-btn {
      height: 100% !important;
      width: 200px;
      box-sizing: border-box;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      font-weight: 600;
      background-color: var(--bg);
    }
  }

  /* 前缀图标 */
  .search-icon {
    width: 20px;
    height: 20px;
    margin-right: 8px;
  }

  /* 右侧竖线分割（默认隐藏由 v-if 控制） */
  .search-divider {
    width: 1px;
    height: 12px;
    background-color: var(--cb1);
    margin: 0 12px;
    flex-shrink: 0;
  }

  /* “搜索”按钮 */
  .search-btn {
    border: none;
    background: transparent;
    color: #4753ff;
    font-size: 16px;
    line-height: 1;
    cursor: pointer;
    padding: 0 4px;
    margin-left: 20px;

    &:hover {
      opacity: 0.85;
    }
  }

  .app-wrapper {
    width: calc(100vw);
    height: calc(100vh);
    min-width: 1440px;
    background-color: #f0f3ff;
    background-image: url("https://qingqingrent.oss-cn-hangzhou.aliyuncs.com/backstage/xiaochengxu/helpcenter/page-bg2.png");
    background-repeat: no-repeat;
    background-position: top center;
    background-size: 100% auto;
    display: flex;
    flex-direction: column;

    .app-content-wrapper {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;

      .help-wrapper {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;

        .page-search {
          width: 100%;
          margin-top: 20px;
          margin-bottom: 40px;
          display: flex;
          flex-direction: column;
          align-items: center;
          flex-shrink: 0;

          .search-title {
            font-size: 40px;
            font-weight: 600;
            color: #15194d;
            margin-bottom: 24px;
          }

          /* placeholder 颜色 */
          .search-input ::v-deep(.el-input__inner::placeholder) {
            color: #737594;
            font-size: 16px;
          }
        }

        .page-bot-wrapper {
          width: 100%;
          flex: 1;
          overflow-y: auto;
          overflow-x: hidden;
          box-sizing: border-box;
          display: flex;
          justify-content: center;

          .page-bot {
            min-height: 100%;
            height: auto;
            display: flex;
            box-sizing: border-box;
            background-color: #ffffff;
            border-radius: 8px 8px 0 0;
            overflow: visible;

            .bot-left {
              height: 100%;
              width: 240px;
              flex-shrink: 0;
              border-right: solid #e5e6eb 1px;
              overflow: hidden;
            }
            .bot-right {
              min-height: 100%;
              height: auto;
              width: 932px;
              flex-shrink: 0;
              overflow-y: auto;
              overflow-x: hidden;
              box-sizing: border-box;
            }
          }
        }

        .page-detail-wrapper {
          width: 100%;
          flex: 1;
          overflow: hidden;
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        }
      }
    }
  }
</style>
